package com.hu.chat.service;

import com.alibaba.fastjson.JSON;
import com.hu.chat.config.BeanUtils;
import com.hu.chat.model.vo.WebSocketMessageVo;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/websocket/{id}")
@Component
public class WebSocketService {
    private static final Map<Integer, Session> userSessionMap = new ConcurrentHashMap<>();
    private final GroupUserService groupUserService = BeanUtils.getBean(GroupUserService.class);

    public static Map<Integer, Session> getUserSessionMap() {
        return userSessionMap;
    }

    // 连接建立成功调用的方法
    @OnOpen
    public void onOpen(@PathParam("id") Integer id, Session session) {
        userSessionMap.put(id, session);
        System.out.println("有新连接加入！当前在线人数为" + userSessionMap.size());
    }

    // 收到客户端消息后调用的方法
    @OnMessage
    public void onMessage(String message) {
        System.out.println("来自客户端的消息:" + message);
        WebSocketMessageVo vo = JSON.parseObject(message, WebSocketMessageVo.class);
        if (vo.getType() == 1) {
            vo.setMessage("私发" + vo.getMessage());
            sendMessage(vo);
        } else {
            vo.setMessage("群发" + vo.getMessage());
            groupMessage(vo);
        }
    }

    // 群聊消息
    public void groupMessage(WebSocketMessageVo vo) {
        for (Integer receiveId : groupUserService.getUserIdListByGroupId(vo.getGroupId())) {
            if (!receiveId.equals(vo.getSendId())) {
                vo.setReceiveId(receiveId);
                sendMessage(vo);
            }
        }
    }

    // 系统消息
    public void systemMessage(Integer receiveId, String message) {
        WebSocketMessageVo vo = new WebSocketMessageVo();
        vo.setType(3);
        vo.setMessage(message);
        if (receiveId == null || receiveId <= 0) {
            for (Integer id : userSessionMap.keySet()) {
                vo.setReceiveId(id);
                sendMessage(vo);
            }
        } else {
            vo.setReceiveId(receiveId);
            sendMessage(vo);
        }
    }

    public void sendMessage(WebSocketMessageVo vo) {
        try {
            Session session = userSessionMap.get(vo.getReceiveId());
            if (session == null) {
                // System.out.println(vo.getReceiveId() + " -- > session is null");
                return;
            }
            // if (vo.getType() == 2) {
            //     vo.setReceiveId(vo.getGroupId());
            // }
            else if (vo.getType() == 2) {
                vo.setSendId(vo.getGroupId());
            }
            session.getBasicRemote().sendText(JSON.toJSONString(vo));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 连接关闭调用的方法
    @OnClose
    public void onClose(@PathParam("id") Integer id) {
        userSessionMap.remove(id);  //从set中删除
        System.out.println("有一连接关闭！当前在线人数为" + userSessionMap.size());
    }

    // 发生错误时调用
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}